package com.spark.tags;

import java.util.Map;

import com.spark.core.SparkContext;
import com.spark.core.XMap;

public class DatePicker extends TriggerField {

	private static final String DEFAULT_TEMPLATES = "datePicker.ftl";
	private static final String DEFAULT_CLASSNAME = "s_dp";

	private static final String PROPERTITY_SIZE = "size";

	protected String getDefaultClass(XMap view, SparkContext context) {
		String className = super.getDefaultClass(view, context);
		StringBuilder sb = new StringBuilder();
		sb.append(className);
		if (!"".equals(className.trim()))
			sb.append(" ");
		sb.append(DEFAULT_CLASSNAME);
		return sb.toString();
	}

	public String getTemplate() {
		return DEFAULT_TEMPLATES;
	}

	public void init(XMap view, SparkContext context) throws Exception {
		super.init(view, context);
		int viewSize = view.getInt(PROPERTITY_SIZE, 1);
		context.addJsonConfig(PROPERTITY_SIZE, viewSize);
		String id = (String) context.get(PROPERTITY_ID);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < viewSize; i++) {
			sb.append("<TD valign='top' id='" + id + "_df" + i + "'></TD>");
		}
		context.put("body", sb.toString());
	}
	
	@SuppressWarnings("unchecked")
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<div class=\"").append(get(map,"className")).append("\" style=\"width:").append(get(map,"width")).append("px;height:").append(get(map,"height")).append("px;").append(get(map,"style")).append("\" id=\"").append(get(map,"id")).append("\">\r");
		sb.append("    <div>\r");
		sb.append("    	<input class=\"s_tf\" stype=\"input\" style=\"width:").append(get(map,"inputWidth")).append("px;line-height:").append(get(map,"lineHeight")).append("px;height:").append(get(map,"inputHeight")).append("px;\" ").append(get(map,"readOnly")).append(" autocomplete=\"off\" value=\"").append(get(map,"value")).append("\" />\r");
		sb.append("    </div>	\r");
		sb.append("    <div class=\"s_tg s_dbtn\" style=\"height:").append(get(map,"trigerHeight")).append("px\" stype=\"trigger\" hidefocus></div>\r");
		sb.append("    <div class=\"s_popup\" stype=\"popup\">\r");
		sb.append("        <table cellspacing=\"2\">\r");
		sb.append("            <tr>\r");
		sb.append("                ").append(get(map,"body"));
		sb.append("            </tr>\r");
		sb.append("        </table>\r");
		sb.append("    </div>\r");
		sb.append("</div>\r");
		sb.append("<script>new Spark.DatePicker(").append(get(map,"config")).append(");</script>\r");
		return sb.toString();
	}
}
